package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.*;
import com.itheima.ydd.dto.ArticleDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/home/index")
@Slf4j
@CrossOrigin
public class FrontIndexController {
    @Autowired
    private IYddArticleService iYddArticleService;

    @Autowired
    private IYddCateService iYddCateService;

    @Autowired
    private IYddUserService iYddUserService;

    @Autowired
    private ISysConfigService iSysConfigService;

    @Autowired
    private IYddTagService iYddTagService;

    @Autowired
    private IYddLinkService iYddLinkService;

    @Autowired
    private IYddAdvimgService iYddAdvimgService;
    /**
     * 登录
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody YddUser yddUser) {
        log.info("登陆用户：{}", yddUser.toString());


        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile,yddUser.getMobile());
        YddUser one = iYddUserService.getOne(wrapper);

        if (one == null) {
            return R.error("账号不存在");
        }
        String password = yddUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))) {
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();


            tokenMap.put("username", one.getUsername());
            tokenMap.put("mobile", one.getMobile());

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);
            return R.success("token",retMap);
        }
        return R.error("密码错误");

    }





    /**
     * md5加密
     *
     * @param password 密码
     */
    private String generatePassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
}
